
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';

typedef ListenerHandler = Future<dynamic> Function(Map<String, dynamic> event);

class SpeechPlay {


  static const String flutter_log = "| SpeechPlay | Flutter | ";

  factory SpeechPlay() => _instance;

  final MethodChannel _methodChannel;

  @visibleForTesting
  SpeechPlay.private(MethodChannel channel) : _methodChannel = channel;

  static final SpeechPlay _instance =
  SpeechPlay.private(const MethodChannel('speech_play'));

  Future<String?> getPlatformVersion() async {
    return await _methodChannel.invokeMethod<String>('getPlatformVersion');
  }

  Future<String?> getExternalFilesDir() async {
    return await _methodChannel.invokeMethod<String>('getExternalFilesDir');
  }

  // 返回语音时长
  Future<dynamic> speechPlay(String path, int startTime, int duration) async {
    return await _methodChannel.invokeMethod("speechPlay", {
      "path": path,
      "startTime": startTime,
      "duration": duration
    });
  }

  Future<double> pausePlay() async {
    return await _methodChannel.invokeMethod("pausePlay");
  }

  Future<void> cancelPause() async {
    return await _methodChannel.invokeMethod("cancelPause");
  }

  Future<void> playSeekTo(int startTime) async{
    return await _methodChannel.invokeMethod("playSeekTo",{
      "startTime": startTime
    });
  }

  // true 扬声器 false 听筒
  Future<void> switchSpeaker(bool enable) async {
    _methodChannel.invokeMethod("switchSpeaker", {
      "enable": enable
    });
  }


  ListenerHandler? _onListenerPlayTime;
  ListenerHandler? _onListenerCompleted;
  ListenerHandler? _onSwitchSpeaker;

  void addEventListener({
    ListenerHandler? onListenerPlayTime,
    ListenerHandler? onListenerCompleted,
    ListenerHandler? onSwitchSpeaker,
  }){
    _onListenerPlayTime = onListenerPlayTime;
    _onListenerCompleted = onListenerCompleted;
    _onSwitchSpeaker = onSwitchSpeaker;
    _methodChannel.setMethodCallHandler(_handleMethod);
  }

  Future<dynamic> _handleMethod(MethodCall call) async {

    switch (call.method) {
      case "onListenerPlayTime":
        return _onListenerPlayTime!(call.arguments.cast<String, dynamic>());
      case "onListenerCompleted":
        return _onListenerCompleted!(call.arguments.cast<String, dynamic>());
      case "onSwitchSpeaker":
        return _onSwitchSpeaker!(call.arguments.cast<String, dynamic>());
      default:
        throw UnsupportedError("Unrecognized Event");
    }
  }

}
